package com.treasure.mall.biz.remote.live.impl;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.live.v20180801.LiveClient;
import com.tencentcloudapi.live.v20180801.models.*;
import com.treasure.mall.biz.config.tencent.TencentConfig;
import com.treasure.mall.biz.entity.live.LiveRoomPO;
import com.treasure.mall.biz.remote.live.TencentLiveService;
import com.treasure.mall.biz.remote.live.TencentTools;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.base.ResultCodeEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * 直播相关服务
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.biz.service.core.live.impl
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/6/11 20:21
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * Copyright 2019-2022 com.treasure.mall.biz.service.core.live.impl Inc. All rights reserved.
 */
@Service
public class TencentLiveServiceImpl implements TencentLiveService {

    @Resource
    private TencentConfig tencentConfig;


    public LiveClient liveClient() {
        // 实例化一个认证对象，入参需要传入腾讯云账户 secretId，secretKey
        Credential cred = new Credential(tencentConfig.getSecretId(), tencentConfig.getSecretKey());

        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("live.tencentcloudapi.com");

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品（以 CVM 为例）的 client 对象
        return new LiveClient(cred, "ap-shanghai", clientProfile);
    }


    @Override
    public Map<String, String> getPushUrl(LiveRoomPO room) throws TencentCloudSDKException, NoSuchAlgorithmException {
        DescribeLivePushAuthKeyRequest request = new DescribeLivePushAuthKeyRequest();
        request.setDomainName(tencentConfig.getLivePushDomain());
        DescribeLivePushAuthKeyResponse response = liveClient().DescribeLivePushAuthKey(request);
        String streamName = room.toStreamName();

        String suffix = TencentTools.getSafeUrl(response.getPushAuthKeyInfo().getMasterAuthKey(), streamName, LocalDateTime.now().plusHours(24));
        String rtmp = MessageFormat.format("rtmp://{0}/live/{1}?{2}"
                , tencentConfig.getLivePushDomain(), room.toStreamName(), suffix);
        Map<String, String> map = new HashMap<>(1);
        map.put("rtmp", rtmp);
        return map;
    }

    /**
     * 设置拉流地址
     *
     * @param room
     */
    @Override
    public ApiResult setupPlayUrl(LiveRoomPO room) {
        try {
            DescribeLivePlayAuthKeyRequest request = new DescribeLivePlayAuthKeyRequest();
            request.setDomainName(tencentConfig.getLivePlayDomain());
            DescribeLivePlayAuthKeyResponse response = liveClient().DescribeLivePlayAuthKey(request);
            String streamName = room.toStreamName();
            String suffix = TencentTools.getSafeUrl(response.getPlayAuthKeyInfo().getAuthKey(), streamName, LocalDateTime.now().plusHours(24));
            return ApiResult.resultWith(ResultCodeEnum.SUCCESS, MessageFormat.format("rtmp://{0}/live/{1}?{2}", tencentConfig.getLivePlayDomain(), streamName, suffix));
        } catch (Exception ex) {
            return ApiResult.errorWith(ResultCodeEnum.THIRD_ERROR);
        }
    }

    /**
     * 关闭推流
     *
     * @param room
     */
    @Override
    public void closeStream(LiveRoomPO room) {
        try {
            DropLiveStreamRequest request = new DropLiveStreamRequest();
            request.setDomainName(tencentConfig.getLivePushDomain());
            request.setAppName("live");
            request.setStreamName(room.toStreamName());
            liveClient().DropLiveStream(request);
        } catch (Exception e) {

        }
    }

    /**
     * 检查直播间流是否是激活状态
     *
     * @param streamName 直播间streamName
     * @return
     */
    @Override
    public boolean describeLiveStreamState(String streamName) {
        try {
            DescribeLiveStreamStateRequest req = new DescribeLiveStreamStateRequest();
            req.setAppName("live");
            req.setDomainName(tencentConfig.getLivePushDomain());
            req.setStreamName(streamName);
            DescribeLiveStreamStateResponse resp = liveClient().DescribeLiveStreamState(req);
            return "active".equals(resp.getStreamState().toLowerCase());
        } catch (Exception ex) {
        }
        return true;
    }
}
